package com.advertisementsystem.aop;

import com.advertisementsystem.Dto.LoginUser;
import com.advertisementsystem.Servie.UserRoleService;
import com.advertisementsystem.vo.UserRoleVO;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.nio.file.AccessDeniedException;

@Aspect
@Component
public class PermissionAspect {

    @Autowired
    private UserRoleService userRoleService;

    @Around("@annotation(requiresPermission)")
    public Object checkPermission(ProceedingJoinPoint point, RequiresPermission requiresPermission) throws Throwable {
        // 获取当前用户
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();

        // 获取用户权限
        UserRoleVO userRoleVO = userRoleService.getUserRoles(loginUser.getUser().getId());

        // 检查权限
        if (!userRoleVO.getPermissions().contains(requiresPermission.value())) {
            throw new AccessDeniedException("没有操作权限");
        }

        return point.proceed();
    }
}
